package 数据结构.search;

import java.util.ArrayList;

/**
 * 二分查找:数组要求有序排列
 */
public class BinarySearch {
    public static void main(String[] args) {
        int arr[] = {1, 9, 11, 1111, 1111, 1233, 1233, 1233};
        ArrayList list = binarySearch2(arr, 0, arr.length - 1, 1111);
        System.out.println(list);
    }

    /**
     * @param arr     数组集合
     * @param left    左边索引
     * @param right   右边索引
     * @param findVal 需要查找的值
     */
    public static int binarySearch(int[] arr, int left, int right, int findVal) {
        //退出递归条件1.找到2.找不到
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        int midVal = arr[mid];

        if (findVal > midVal) {
            return binarySearch(arr, mid + 1, right, findVal);
        } else if (findVal < midVal) {
            return binarySearch(arr, left, mid - 1, findVal);
        } else {
            return mid;
        }
    }

    //返回全部的数据
    public static ArrayList binarySearch2(int[] arr, int left, int right, int findVal) {
        //退出递归条件1.找到2.找不到
        if (left > right) {
            return new ArrayList();
        }
        int mid = (left + right) / 2;
        int midVal = arr[mid];

        if (findVal > midVal) {
            return binarySearch2(arr, mid + 1, right, findVal);
        } else if (findVal < midVal) {
            return binarySearch2(arr, left, mid - 1, findVal);
        } else {
            ArrayList<Object> resultList = new ArrayList<>();
            int temp = mid - 1;
            while (temp > 0 && arr[temp] == findVal) {
                resultList.add(temp);
                temp -= 1;//temp左移
            }

            resultList.add(mid);
            temp = mid + 1;
            while (temp < arr.length && arr[temp] == findVal) {
                resultList.add(temp);
                temp += 1;
            }
            return resultList;
        }

    }
}
